package com.peng.leetcode.minknum;

import java.util.Arrays;

/**
 * MinkNum1
 *
 * @author lupeng
 * Created on 2022-04-12
 */
public class MinkNum1 {

    public static void main(String[] args) {
        int[] arr = new int[]{4, 5, 3, 2, 1};
        int[] minKNum = new MinkNum1().findMinKNum(arr, 3);
        System.out.println(Arrays.toString(minKNum));
    }


    public int[] findMinKNum(int[] arr, int k) {
        doFind(arr, 0, arr.length - 1, k);
        int[] result = new int[k];
        System.arraycopy(arr, 0, result, 0, k);
        return result;
    }

    private void doFind(int[] arr, int left, int right, int k) {
        int partitionIndex = partition(arr, left, right, k);
        if (partitionIndex > k - 1) {
            doFind(arr, left, partitionIndex - 1, k);
        } else if (partitionIndex < k - 1) {
            doFind(arr, partitionIndex + 1, right, k);
        }
    }

    private int partition(int[] arr, int left, int right, int k) {
        int value = arr[right];
        int i = left;
        int j = left;
        while (j < right) {
            if (arr[j] < value) {
                swap(arr, i, j);
                i++;
            }
            j++;
        }
        swap(arr, i, right);
        return i;
    }

    public void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }


}
